{% extends 'base.html' %}

{% block title %}推送执行列表 - 资讯聚合平台{% endblock %}

{% block page_title %}推送执行列表{% endblock %}

{% block page_actions %}
<button class="btn" id="add-task-btn">
    <i class="fas fa-plus"></i> 添加推送任务
</button>
{% endblock %}

{% block content %}
<div class="task-list">
    {% if tasks %}
        <div class="task-cards">
            {% for task in tasks %}
                <div class="task-card {% if task.is_active %}active{% else %}inactive{% endif %}">
                    <div class="task-header">
                        <h3>{{ task.keyword.keyword }}</h3>
                        <div class="task-actions">
                            <button class="edit-btn" data-id="{{ task.id }}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="delete-btn" data-id="{{ task.id }}">
                                <i class="fas fa-trash"></i>
                            </button>
                            <div class="toggle-switch">
                                <input type="checkbox" id="toggle-{{ task.id }}" class="toggle-input" {% if task.is_active %}checked{% endif %} data-id="{{ task.id }}">
                                <label for="toggle-{{ task.id }}" class="toggle-label"></label>
                            </div>
                        </div>
                    </div>
                    <div class="task-body">
                        <div class="task-item">
                            <span class="label">推送类型:</span>
                            <span class="value">{{ task.get_task_type_display }}</span>
                        </div>
                        <div class="task-item">
                            <span class="label">推送目标:</span>
                            <span class="value">
                                {% if task.task_type == 'email' %}
                                    {{ task.email_config.name }}
                                {% elif task.task_type == 'dingtalk' %}
                                    {{ task.dingtalk_config.name }}
                                {% elif task.task_type == 'feishu' %}
                                    {{ task.feishu_config.name }}
                                {% endif %}
                            </span>
                        </div>
                        <div class="task-item">
                            <span class="label">执行时间:</span>
                            <span class="value">{{ task.schedule_time|date:"Y-m-d H:i" }}</span>
                        </div>
                        <div class="task-item">
                            <span class="label">状态:</span>
                            <span class="value status-badge {% if task.is_active %}active{% else %}inactive{% endif %}">
                                {{ task.is_active|yesno:"启用,禁用" }}
                            </span>
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>
    {% else %}
        <div class="empty-state">
            <i class="fas fa-tasks fa-3x"></i>
            <p>暂无推送任务</p>
            <p class="hint">点击右上角"添加推送任务"按钮创建新任务</p>
        </div>
    {% endif %}
</div>

<!-- 添加/编辑任务模态框 -->
<div class="modal" id="task-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modal-title">添加推送任务</h3>
            <button class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <form id="task-form" method="post">
                {% csrf_token %}
                <input type="hidden" name="task_id" id="task_id">
                <div class="form-group">
                    <label for="keyword">关键词</label>
                    <select id="keyword" name="keyword" required>
                        <option value="">-- 选择关键词 --</option>
                        {% for keyword in keywords %}
                            <option value="{{ keyword.id }}">{{ keyword.keyword }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="form-group">
                    <label for="task_type">推送类型</label>
                    <select id="task_type" name="task_type" required>
                        <option value="">-- 选择推送类型 --</option>
                        <option value="email">邮箱推送</option>
                        <option value="dingtalk">钉钉推送</option>
                        <option value="feishu">飞书推送</option>
                    </select>
                </div>
                
                <!-- 邮箱配置选择 (默认隐藏) -->
                <div class="form-group config-select" id="email-config-group" style="display: none;">
                    <label for="email_config">邮箱配置</label>
                    <select id="email_config" name="email_config">
                        <option value="">-- 选择邮箱配置 --</option>
                        {% for config in email_configs %}
                            <option value="{{ config.id }}">{{ config.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                
                <!-- 钉钉配置选择 (默认隐藏) -->
                <div class="form-group config-select" id="dingtalk-config-group" style="display: none;">
                    <label for="dingtalk_config">钉钉配置</label>
                    <select id="dingtalk_config" name="dingtalk_config">
                        <option value="">-- 选择钉钉配置 --</option>
                        {% for config in dingtalk_configs %}
                            <option value="{{ config.id }}">{{ config.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                
                <!-- 飞书配置选择 (默认隐藏) -->
                <div class="form-group config-select" id="feishu-config-group" style="display: none;">
                    <label for="feishu_config">飞书配置</label>
                    <select id="feishu_config" name="feishu_config">
                        <option value="">-- 选择飞书配置 --</option>
                        {% for config in feishu_configs %}
                            <option value="{{ config.id }}">{{ config.name }}</option>
                        {% endfor %}
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="schedule_time">执行时间</label>
                    <input type="datetime-local" id="schedule_time" name="schedule_time" required>
                </div>
                
                <div class="form-group checkbox">
                    <input type="checkbox" id="is_active" name="is_active" checked>
                    <label for="is_active">启用任务</label>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn-cancel">取消</button>
                    <button type="submit" class="btn-submit">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal" id="delete-modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>确认删除</h3>
            <button class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
            <p>确定要删除此推送任务吗？此操作不可撤销。</p>
            <div class="form-actions">
                <button type="button" class="btn-cancel">取消</button>
                <button type="button" class="btn-delete">删除</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
    /* 任务列表样式 */
    .task-list {
        margin-top: 20px;
    }
    
    .task-cards {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 25px;
    }
    
    .task-card {
        background: rgba(255, 255, 255, 0.25);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border-radius: 25px;
        overflow: hidden;
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
        transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
        border: 1px solid rgba(255, 255, 255, 0.3);
        position: relative;
    }
    
    .task-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
    }
    
    .task-card.inactive {
        opacity: 0.75;
    }
    
    .task-header {
        background: linear-gradient(135deg, var(--primary-green), var(--secondary-green));
        color: white;
        padding: 18px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        position: relative;
        overflow: hidden;
    }
    
    .task-header::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
        clip-path: polygon(0 0, 100% 0, 100% 70%, 0 100%);
    }
    
    .task-card.inactive .task-header {
        background: linear-gradient(135deg, #a0a0a0, #c0c0c0);
    }
    
    .task-header h3 {
        margin: 0;
        font-size: 1.25em;
        font-weight: 600;
        position: relative;
        z-index: 1;
    }
    
    .task-actions {
        display: flex;
        gap: 12px;
        align-items: center;
        position: relative;
        z-index: 1;
    }
    
    .task-actions button {
        background: rgba(255, 255, 255, 0.25);
        border: none;
        border-radius: 50%;
        width: 34px;
        height: 34px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    
    .task-actions button:hover {
        background: rgba(255, 255, 255, 0.4);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
    }
    
    .task-body {
        padding: 20px;
    }
    
    .task-item {
        margin-bottom: 15px;
        display: flex;
        flex-direction: column;
    }
    
    .task-item:last-child {
        margin-bottom: 0;
    }
    
    .task-item .label {
        font-size: 0.9em;
        color: #7a938b;
        margin-bottom: 6px;
        font-weight: 500;
    }
    
    .task-item .value {
        font-weight: 600;
        color: var(--dark-gray);
    }
    
    .status-badge {
        display: inline-block;
        padding: 5px 12px;
        border-radius: 15px;
        font-size: 0.85em;
        font-weight: 600;
        letter-spacing: 0.5px;
    }
    
    .status-badge.active {
        background-color: rgba(126, 211, 33, 0.15);
        color: var(--primary-green);
        box-shadow: 0 2px 8px rgba(126, 211, 33, 0.2);
    }
    
    .status-badge.inactive {
        background-color: rgba(160, 160, 160, 0.15);
        color: #7a7a7a;
        box-shadow: 0 2px 8px rgba(160, 160, 160, 0.2);
    }
    
    .empty-state {
        text-align: center;
        padding: 60px 0;
        color: #7a938b;
    }
    
    .empty-state i {
        margin-bottom: 25px;
        opacity: 0.5;
        font-size: 3.5em;
    }
    
    .empty-state p {
        font-size: 1.2em;
        margin: 0 0 10px;
    }
    
    .empty-state .hint {
        font-size: 0.95em;
        opacity: 0.7;
        margin-top: 15px;
    }
    
    /* 开关样式 */
    .toggle-switch {
        position: relative;
        display: inline-block;
        width: 52px;
        height: 26px;
    }
    
    .toggle-input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    
    .toggle-label {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(255, 255, 255, 0.5);
        transition: .4s;
        border-radius: 26px;
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    
    .toggle-label:before {
        position: absolute;
        content: "";
        height: 20px;
        width: 20px;
        left: 3px;
        bottom: 3px;
        background-color: white;
        transition: .4s;
        border-radius: 50%;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
    
    .toggle-input:checked + .toggle-label {
        background-color: var(--primary-green);
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
    }
    
    .toggle-input:checked + .toggle-label:before {
        transform: translateX(26px);
    }
    
    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        align-items: center;
        justify-content: center;
    }
    
    .modal-content {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border-radius: 30px;
        width: 90%;
        max-width: 520px;
        box-shadow: 0 15px 40px rgba(0, 0, 0, 0.15);
        animation: modal-in 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
        border: 1px solid rgba(255, 255, 255, 0.3);
        overflow: hidden;
    }
    
    @keyframes modal-in {
        from {
            opacity: 0;
            transform: translateY(-40px) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translateY(0) scale(1);
        }
    }
    
    .modal-header {
        padding: 20px 25px;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: rgba(255, 255, 255, 0.5);
    }
    
    .modal-header h3 {
        margin: 0;
        color: var(--dark-gray);
        font-size: 1.4em;
        font-weight: 600;
    }
    
    .close-btn {
        background: none;
        border: none;
        font-size: 1.6em;
        cursor: pointer;
        color: #7a938b;
        transition: color 0.3s;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
    }
    
    .close-btn:hover {
        color: var(--dark-gray);
        background: rgba(0, 0, 0, 0.05);
    }
    
    .modal-body {
        padding: 25px;
    }
    
    .form-group {
        margin-bottom: 22px;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 10px;
        color: var(--dark-gray);
        font-weight: 500;
        font-size: 0.95em;
    }
    
    .form-group input,
    .form-group select {
        width: 100%;
        padding: 14px 18px;
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: 15px;
        font-size: 1em;
        transition: all 0.3s;
        background: rgba(255, 255, 255, 0.8);
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.03);
    }
    
    .form-group input:focus,
    .form-group select:focus {
        border-color: var(--primary-green);
        outline: none;
        box-shadow: 0 0 0 3px rgba(126, 211, 33, 0.2);
        background: rgba(255, 255, 255, 1);
    }
    
    .form-group.checkbox {
        display: flex;
        align-items: center;
        margin-top: 10px;
    }
    
    .form-group.checkbox input {
        width: auto;
        margin-right: 12px;
        height: 18px;
        width: 18px;
    }
    
    .form-group.checkbox label {
        margin-bottom: 0;
        cursor: pointer;
    }
    
    .form-actions {
        display: flex;
        justify-content: flex-end;
        gap: 15px;
        margin-top: 30px;
    }
    
    .btn-cancel {
        background: rgba(0, 0, 0, 0.05);
        color: var(--dark-gray);
        border: none;
        padding: 12px 24px;
        border-radius: 20px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.3s;
        font-size: 1em;
    }
    
    .btn-cancel:hover {
        background: rgba(0, 0, 0, 0.1);
    }
    
    .btn-submit {
        background: linear-gradient(135deg, var(--primary-green), var(--secondary-green));
        color: white;
        border: none;
        padding: 12px 28px;
        border-radius: 20px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(126, 211, 33, 0.3);
        font-size: 1em;
        position: relative;
        overflow: hidden;
    }
    
    .btn-submit::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
        clip-path: polygon(0 0, 100% 0, 100% 70%, 0 100%);
    }
    
    .btn-submit:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(126, 211, 33, 0.4);
    }
    
    .btn-submit:active {
        transform: translateY(-1px);
    }
    
    .btn-delete {
        background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
        color: white;
        border: none;
        padding: 12px 28px;
        border-radius: 20px;
        cursor: pointer;
        font-weight: 600;
        transition: all 0.3s;
        box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
        font-size: 1em;
        position: relative;
        overflow: hidden;
    }
    
    .btn-delete::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
        clip-path: polygon(0 0, 100% 0, 100% 70%, 0 100%);
    }
    
    .btn-delete:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
    }
    
    /* 配置组样式 */
    .config-select {
        transition: all 0.3s ease;
        opacity: 0;
        transform: translateY(10px);
        height: 0;
        margin: 0;
        overflow: hidden;
    }
    
    .config-select[style*="display: block"] {
        opacity: 1;
        transform: translateY(0);
        height: auto;
        margin-bottom: 22px;
        animation: fade-in 0.3s ease-out;
    }
    
    @keyframes fade-in {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
</style>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const taskModal = document.getElementById('task-modal');
        const deleteModal = document.getElementById('delete-modal');
        const addTaskBtn = document.getElementById('add-task-btn');
        const closeBtns = document.querySelectorAll('.close-btn');
        const cancelBtns = document.querySelectorAll('.btn-cancel');
        const taskForm = document.getElementById('task-form');
        const modalTitle = document.getElementById('modal-title');
        const taskIdInput = document.getElementById('task_id');
        const keywordSelect = document.getElementById('keyword');
        const taskTypeSelect = document.getElementById('task_type');
        const emailConfigGroup = document.getElementById('email-config-group');
        const dingtalkConfigGroup = document.getElementById('dingtalk-config-group');
        const feishuConfigGroup = document.getElementById('feishu-config-group');
        const emailConfigSelect = document.getElementById('email_config');
        const dingtalkConfigSelect = document.getElementById('dingtalk_config');
        const feishuConfigSelect = document.getElementById('feishu_config');
        const scheduleTimeInput = document.getElementById('schedule_time');
        const isActiveCheckbox = document.getElementById('is_active');
        const deleteConfirmBtn = deleteModal.querySelector('.btn-delete');
        const editBtns = document.querySelectorAll('.edit-btn');
        const deleteBtns = document.querySelectorAll('.delete-btn');
        const toggleInputs = document.querySelectorAll('.toggle-input');

        let currentTaskId = null;
        let currentDeleteId = null;

        function openModal(modal) {
            modal.style.display = 'flex';
            setTimeout(() => modal.classList.add('show'), 10);
        }

        function closeModal(modal) {
            modal.classList.remove('show');
            setTimeout(() => modal.style.display = 'none', 300);
        }

        function resetForm() {
            taskForm.reset();
            taskIdInput.value = '';
            modalTitle.textContent = '添加推送任务';
            isActiveCheckbox.checked = true; // 默认启用
            hideAllConfigGroups();
            
            // 设置默认执行时间为当前时间
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            scheduleTimeInput.value = `${year}-${month}-${day}T${hours}:${minutes}`;
        }

        function hideAllConfigGroups() {
            emailConfigGroup.style.display = 'none';
            dingtalkConfigGroup.style.display = 'none';
            feishuConfigGroup.style.display = 'none';
            emailConfigSelect.removeAttribute('required');
            dingtalkConfigSelect.removeAttribute('required');
            feishuConfigSelect.removeAttribute('required');
        }

        function showConfigGroup(type) {
            hideAllConfigGroups();
            if (type === 'email') {
                emailConfigGroup.style.display = 'block';
                emailConfigSelect.setAttribute('required', 'required');
            } else if (type === 'dingtalk') {
                dingtalkConfigGroup.style.display = 'block';
                dingtalkConfigSelect.setAttribute('required', 'required');
            } else if (type === 'feishu') {
                feishuConfigGroup.style.display = 'block';
                feishuConfigSelect.setAttribute('required', 'required');
            }
        }

        // 添加任务按钮点击事件
        addTaskBtn.addEventListener('click', function() {
            resetForm();
            openModal(taskModal);
        });

        // 关闭模态框按钮事件
        closeBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                closeModal(taskModal);
                closeModal(deleteModal);
            });
        });

        // 取消按钮事件
        cancelBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                closeModal(taskModal);
                closeModal(deleteModal);
            });
        });

        // 推送类型选择事件
        taskTypeSelect.addEventListener('change', function() {
            showConfigGroup(this.value);
        });

        // 编辑按钮点击事件
        editBtns.forEach(button => {
            button.addEventListener('click', function() {
                const taskId = this.dataset.id;
                modalTitle.textContent = '编辑推送任务';
                taskIdInput.value = taskId;

                fetch(`/push_notifications/push_tasks/${taskId}/`)
                    .then(response => response.json())
                    .then(data => {
                        keywordSelect.value = data.keyword;
                        taskTypeSelect.value = data.task_type;
                        showConfigGroup(data.task_type);
                        if (data.task_type === 'email') {
                            emailConfigSelect.value = data.email_config;
                        } else if (data.task_type === 'dingtalk') {
                            dingtalkConfigSelect.value = data.dingtalk_config;
                        } else if (data.task_type === 'feishu') {
                            feishuConfigSelect.value = data.feishu_config;
                        }
                        scheduleTimeInput.value = data.schedule_time;
                        isActiveCheckbox.checked = data.is_active;
                        openModal(taskModal);
                    })
                    .catch(error => console.error('Error fetching task details:', error));
            });
        });

        // 删除按钮点击事件
        deleteBtns.forEach(button => {
            button.addEventListener('click', function() {
                currentDeleteId = this.dataset.id;
                openModal(deleteModal);
            });
        });

        // 确认删除按钮事件
        deleteConfirmBtn.addEventListener('click', function() {
            if (currentDeleteId) {
                fetch(`/push_notifications/push_tasks/${currentDeleteId}/delete/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => {
                    if (response.ok) {
                        window.location.reload(); // 刷新页面以显示更新后的列表
                    } else {
                        console.error('Error deleting task');
                    }
                })
                .catch(error => console.error('Error:', error));
            }
            closeModal(deleteModal);
        });

        // 启用/禁用切换事件
        toggleInputs.forEach(toggle => {
            toggle.addEventListener('change', function() {
                const taskId = this.dataset.id;
                fetch(`/push_notifications/push_tasks/${taskId}/toggle/`, {
                    method: 'POST',
                    headers: {
                        'X-CSRFToken': '{{ csrf_token }}',
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        const card = this.closest('.task-card');
                        const statusBadge = card.querySelector('.status-badge');
                        if (data.is_active) {
                            card.classList.remove('inactive');
                            card.classList.add('active');
                            statusBadge.textContent = '启用';
                            statusBadge.classList.remove('inactive');
                            statusBadge.classList.add('active');
                        } else {
                            card.classList.remove('active');
                            card.classList.add('inactive');
                            statusBadge.textContent = '禁用';
                            statusBadge.classList.remove('active');
                            statusBadge.classList.add('inactive');
                        }
                    }
                })
                .catch(error => console.error('Error toggling task status:', error));
            });
        });
        
        // 点击模态框外部关闭
        window.addEventListener('click', function(event) {
            if (event.target === taskModal) {
                taskModal.style.display = 'none';
            }
            if (event.target === deleteModal) {
                deleteModal.style.display = 'none';
            }
        });
    });
</script>
{% endblock %}
